package com.reactim.message.task;

import com.reactim.message.metrics.ProtobufPerformanceMetrics;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 性能报告定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "reactim.performance.report.enabled", havingValue = "true", matchIfMissing = true)
public class PerformanceReportTask {
    
    private final ProtobufPerformanceMetrics performanceMetrics;
    
    /**
     * 每5分钟输出一次性能报告
     */
    @Scheduled(fixedRate = 300000) // 5分钟
    public void reportPerformanceMetrics() {
        try {
            ProtobufPerformanceMetrics.PerformanceReport report = performanceMetrics.getPerformanceReport();
            
            // 只有在有数据时才输出报告
            if (report.getTotalMessages() > 0) {
                log.info("=== Protobuf性能监控报告 ===");
                log.info(report.toString());
                log.info("========================");
            }
        } catch (Exception e) {
            log.error("生成性能报告失败", e);
        }
    }
    
    /**
     * 每小时输出一次详细的性能统计
     */
    @Scheduled(fixedRate = 3600000) // 1小时
    public void reportDetailedMetrics() {
        try {
            ProtobufPerformanceMetrics.PerformanceReport report = performanceMetrics.getPerformanceReport();
            
            if (report.getTotalMessages() > 0) {
                log.info("=== 详细性能统计报告 ===");
                log.info("处理消息总数: {}", report.getTotalMessages());
                log.info("数据传输统计:");
                log.info("  - 原始数据总量: {} KB", report.getTotalOriginalBytes() / 1024.0);
                log.info("  - 压缩数据总量: {} KB", report.getTotalCompressedBytes() / 1024.0);
                log.info("  - 节省空间: {} KB ({:.2f}%)", 
                    (report.getTotalOriginalBytes() - report.getTotalCompressedBytes()) / 1024.0,
                    (1.0 - report.getCompressionRatio()) * 100);
                
                log.info("性能指标:");
                log.info("  - 平均压缩耗时: {:.2f} ms", report.getAverageCompressionTime());
                log.info("  - 平均解压缩耗时: {:.2f} ms", report.getAverageDecompressionTime());
                log.info("  - 平均Proto转实体耗时: {:.2f} ms", report.getAverageProtoToEntityTime());
                log.info("  - 平均实体转Proto耗时: {:.2f} ms", report.getAverageEntityToProtoTime());
                
                if (report.getConversionErrors() > 0) {
                    log.warn("转换错误次数: {}", report.getConversionErrors());
                }
                
                log.info("======================");
            }
        } catch (Exception e) {
            log.error("生成详细性能报告失败", e);
        }
    }
}